<?php
/**
 * 相关货品的处理
 *
 * @author chenping<chenping@shopex.cn>
 */

class inventorydepth_stock_products {

    public static $products = array();

    public static $branch_products = array();

    public static $branches = array();

    function __construct($app)
    {
        $this->app = $app;
        # base_kvstore::config_persistent(false);
    }

    public function set_products($products) 
    {
        self::$products = $products;
    }

    public function set_branch_products($branch_products) 
    {
        self::$branch_products = $branch_products;
    }

    public function set_branches($branches) 
    {
        self::$branches = $branches;
    }

    /**
     * 计算库存时，将货品相关信息记内存
     *
     * @return void
     * @author 
     **/
    public function store_products($product_bn,$data)
    {
        base_kvstore::instance('inventorydepth/local/products')->store('product-'.$product_bn,$data);
    }

    /**
     * @description 从内存中删除货品
     * @access public
     * @param void
     * @return void
     */
    public function delete_products($product_bn) 
    {
        base_kvstore::instance('inventorydepth/local/products')->delete('product-'.$product_bn);
    }

    /**
     * 从内存中读货品
     *
     * @return void
     * @author 
     **/
    public function fetch_products($product_bn)
    {
        if (self::$products[$product_bn]) {
            return self::$products[$product_bn];
        }

        if(!$data)
        {
            $salesMaterialObj = app::get('material')->model('sales_material');
            $basicMaterialStockObj = app::get('material')->model('basic_material_stock');
            $salesMLib = kernel::single('material_sales_material');

            $data    = $salesMaterialObj->dump(array('sales_material_bn'=>$product_bn, 'sales_material_type'=>1), 'sm_id,sales_material_name,sales_material_bn,shop_id');
            $bindBasicMInfos = $salesMLib->getBasicMBySalesMId($data['sm_id']);
            if($bindBasicMInfos){
                $salesExtInfo = $basicMaterialStockObj->dump(array('bm_id'=>$bindBasicMInfos[0]['bm_id']),'bm_id,store,store_freeze,max_store_lastmodify,last_modified');
                if($salesExtInfo){
                    $data = array_merge($data,$salesExtInfo);
                }
            }
        }
        
        self::$products[$product_bn] = $data;
        return $data;
    }

    /**
     * 从内存中读仓库对应货品关系
     *
     * @return void
     * @author 
     **/
    public function fetch_branch_products($branch_bn,$product_bn)
    {
        if (self::$branch_products[$branch_bn][$product_bn]) {
            return self::$branch_products[$branch_bn][$product_bn];
        }
        
        if ($this->batch) { return false; }

        $branch = $this->fetch_branch($branch_bn);
        $branch_id = $branch['branch_id'];

        $product = $this->fetch_products($product_bn);
        $product_id    = $product['bm_id'];
        
        # 如果没有命中
        if (!$data) {
            if ($product_id && $branch_id) {        
                $data = app::get('ome')->model('branch_product')->select()->columns('branch_id,product_id,store,store_freeze,last_modified,arrive_store,safe_store,is_locked')
                        ->where('branch_id=?',$branch_id)
                        ->where('product_id=?',$product_id)->instance()->fetch_row();
                
                //识别物料是否保质期物料，是否自有仓储，获取失效的仓库物料库存数，和原总库存做减法
                $branchLib = kernel::single('ome_branch');
                $channelLib = kernel::single('channel_func');
                $wms_id = $branchLib->getWmsIdById($branch_id);
                if($wms_id){
                    //是否自有仓储
                    $is_selfWms = $channelLib->isSelfWms($wms_id);
                    if($is_selfWms){
                        //是否保质期物料
                        $basicMStorageLifeLib = kernel::single('material_storagelife');
                        $is_use_expire = $basicMStorageLifeLib->checkStorageLifeById($product_id);
                        if($is_use_expire){
                            $expire_store = $basicMStorageLifeLib->getExpireStorageLifeStore($branch_id, $product_id);
                            if($expire_store){
                                $data['store'] = $data['store'] - $expire_store;
                            }
                        }
                    }
                }

            }
        }

        self::$branch_products[$branch_bn][$product_bn] = $data;

        return $data;
    }

    /**
     * @description 仓库编号与ID的对应关系
     * @access public
     * @param void
     * @return void
     */
    public function store_branch($branch_bn,$data) 
    {
        base_kvstore::instance('inventorydepth/local/branch')->store('branch-'.$branch_bn,$data);
    }

    /**
     * @description 读取仓库信息
     * @access public
     * @param void
     * @return void
     */
    public function fetch_branch($branch_bn) 
    {
        if (self::$branches[$branch_bn]) {
            return self::$branches[$branch_bn];
        }
        
        if (!$data) {
            $data = app::get('ome')->model('branch')->select()->columns('branch_id,branch_bn')->where('branch_bn=?',$branch_bn)->instance()->fetch_row();
        }
    
        self::$branches[$branch_bn] = $data;
        return $data;
    }

    public function writeMemory($products) 
    {
        $salesMaterialObj = app::get('material')->model('sales_material');#销售物料 ExBOY
        $salesMLib = kernel::single('material_sales_material');
        $product_ids = array();
        $sm_ids    = array();

        foreach ($products as $key => $product)
        {
            $sm_ids[]    = $product['sm_id'];
            $sm_bns[$product['sm_id']] = $product['sales_material_bn'];
        }

        //根据销售物料ids获取对应的基础物料
        $sales_material_list    = array();
        $product_list    = $salesMLib->getBasicMBySalesMIds($sm_ids);
        foreach ($product_list as $sm_id => $sm_items)
        {
            foreach ($sm_items as $temp_key => $bm_item)
            {
                $bm_id                  = $bm_item['bm_id'];
                $product_ids[$bm_id]    = $bm_id;
                
                $sales_material_list[$sm_id]    = $bm_id;
            }
        }
        
        //获取仓库信息数组
        $branches = app::get('ome')->model('branch')->select()->columns('branch_id,branch_bn,attr')->instance()->fetch_all();
        foreach ($branches as $key=>$branch) {
            self::$branches[$branch['branch_bn']] = $branch;
            $branch_ids[$branch['branch_id']] = $branch['branch_bn'];
        }
        
        $branchLib = kernel::single('ome_branch');
        $channelLib = kernel::single('channel_func');
        $basicMStorageLifeLib = kernel::single('material_storagelife');
        
        # 仓库货品
        $product_branch_list    = array();
        $bpModel = app::get('ome')->model('branch_product');
        $branch_products = $bpModel->getList('*',array('product_id'=>$product_ids));
        foreach ($branch_products as $key=>$bp) {
            
            $branch_bn = $branch_ids[$bp['branch_id']];

            #识别物料是否保质期物料，是否自有仓储，获取失效的仓库物料库存数，和原总库存做减法
            $branch_id    = $bp['branch_id'];
            $product_id   = $bp['product_id'];
            $wms_id       = $branchLib->getWmsIdById($branch_id);
            
            if($wms_id)
            {
                //是否自有仓储
                $is_selfWms = $channelLib->isSelfWms($wms_id);
                if($is_selfWms)
                {
                    //是否保质期物料
                    $is_use_expire = $basicMStorageLifeLib->checkStorageLifeById($product_id);
                    if($is_use_expire){
                        $expire_store = $basicMStorageLifeLib->getExpireStorageLifeStore($branch_id, $product_id);
                        if($expire_store){
                            $bp['store'] = $bp['store'] - $expire_store;
                        }
                    }
                }
            }
            
            $product_branch_list[$product_id][$branch_bn]    = $bp;
        }

        #仓库库存关联到销售物料
        foreach ($sales_material_list as $sm_id => $bm_id)
        {
            if(isset($product_branch_list[$bm_id]))
            {
                foreach ($product_branch_list[$bm_id] as $branch_bn => $bp)
                {
                    $sales_material_bn    = $sm_bns[$sm_id];
                    self::$branch_products[$branch_bn][$sales_material_bn]    = $bp;
                }
            }
        }
        
        $this->batch = true;
    }
    
    public function resetVar() 
    {
        self::$products = self::$branches = self::$branch_products = array();
        $this->batch = false;
        return $this;
    }
    
    /**
     * 从内存中读仓库对应货品关系[销售物料对应所有基础物料]
     *
     * @return void
     * @author
     **/
    public function fetch_branch_basic_material($branch_bn, $sales_material_bn)
    {
        if (self::$branch_products[$branch_bn][$sales_material_bn]) {
            return self::$branch_products[$branch_bn][$sales_material_bn];
        }
        
        if ($this->batch) { return false; }
        
        $branch = $this->fetch_branch($branch_bn);
        
        $branch_id = $branch['branch_id'];
        
        $product = $this->fetch_products($sales_material_bn);
        $sm_ids = $product['sm_id'];
        
        #获取销售物料对应的基础物料明细
        $product_id    = array();
        $salesMLib = kernel::single('material_sales_material');
        $get_product    = $salesMLib->getBasicMBySalesMId($sm_ids);
        foreach ($get_product as $key => $value)
        {
            $product_id[] = $value['bm_id'];
        }
        
        # 如果没有命中
        if (!$data) {
            if ($product_id && $branch_id) {
                #计算所有基础物料对应的仓库库存之和
                $oBranchProduct = app::get('ome')->model('branch_product');
                $field       = 'branch_id,product_id,store,store_freeze,last_modified,arrive_store,safe_store,is_locked';
                $dataList    = $oBranchProduct->getList($field, array('branch_id'=>$branch_id, 'product_id'=>$product_id));
                
                $data     = array();
                $branch_store    = array();
                foreach ($dataList as $key => $val)
                {
                    $branch_store['store']    += $val['store'];
                    $branch_store['store_freeze']    += $val['store_freeze'];
                    
                    $data    = $val;
                    $data['store']    = $branch_store['store'];
                    $data['store_freeze']    = $branch_store['store_freeze'];
                }
            }
        }
        
        self::$branch_products[$branch_bn][$sales_material_bn] = $data;
        
        return $data;
    }
}
